package com.jit.app.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import com.jit.app.model.Constants;
import com.jit.app.repository.DownloadInfoRepository;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadService extends Service {

    Map<String,Double> downloadProcess = new HashMap<>();//存储所有apk的下载进度（key是包名，value是进度）
    List<Handler> handlers = new ArrayList<>();//需要发送下载进度消息的所有Handler


    DownloadInfoRepository downloadInfoRepository;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        downloadInfoRepository = new DownloadInfoRepository(this);
        return new DownloadBinder(this);
    }

    /**
     * 下载
     */
    public void download(String pack, String downloadLink){
        downloadProcess.put(pack, 0.0);
        downloading(pack,downloadLink);
    }

    private void downloading(final String pack, String downloadLink){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(Constants.HOST.FILE_HOST+downloadLink)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                File dir = new File(DownloadService.this.getFilesDir(),"downloads");
                if(!dir.exists()){
                    dir.mkdirs();
                }
                String filename = System.currentTimeMillis()+".apk";
                File file = new File(dir, filename);
                OutputStream out = new FileOutputStream(file);
                InputStream inputStream = response.body().byteStream();
                long length = response.body().contentLength();//文件大小
                long dlLength = 0;
                byte[] buf = new byte[1024];
                int len = -1;
                while((len=inputStream.read(buf))!=-1){
                    out.write(buf,0,len);
                    //进度变化
                    dlLength += len;
                    double precess = dlLength*1.0/length;
                    downloadProcess.put(pack, precess);
                    Message message = new Message();
                    message.what = Constants.MessageWhat.PROCESS_CHANGE;
                    Bundle bundle = new Bundle();
                    bundle.putString("pack", pack);
                    bundle.putDouble("process", precess);
                    message.setData(bundle);
                    for(Handler handler : handlers){
                        handler.sendMessage(message);
                    }
                }
                out.close();
                inputStream.close();

                //下载完毕的消息
                Message message = new Message();
                message.what = Constants.MessageWhat.DOWNLOAD_COMPLETE;
                Bundle bundle = new Bundle();
                bundle.putString("pack", pack);
                bundle.putString("apkPath", file.getAbsolutePath());
                message.setData(bundle);
                for(Handler handler : handlers){
                    handler.sendMessage(message);
                }
                //存储到数据库
                downloadInfoRepository.addDownloadInfo(pack,file.getAbsolutePath());
                downloadProcess.remove(pack);
            }
        });
    }

}
